package com.mr.security.web.commons.validate;
import com.mr.security.web.commons.exception.ValidateCodeException;
import com.mr.security.web.commons.utils.Constants;
import com.mr.security.web.commons.utils.ValidateCodeEnum;
import com.mr.security.web.commons.validate.entity.ValidateCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Map;

/**
 * @author (作者) ma_rui
 * @version V1.0
 * @Description: TODO(描述): 验证码校验逻辑处理器抽象实现类
 * @date 2019/1/25 0025 下午 3:53
 */
@Slf4j
public abstract class AbstractValidateCodeProcessor<T extends ValidateCode> implements IValidateCodeProcessor {


    // 采用spring依赖查询的技巧（系统启动的时候会将所有IValidateCodeGenerate接口实现（注入Bean的）
    // 的名字加载到map中，利用此特性来选择校验的类型image或sms等）
    // 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现
    @Autowired
    private Map<String, IValidateCodeGenerator> validateCodeGenerators;


    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述): 创建验证码
    * @date 2019/1/25 0025 下午 4:15
    */
    @Override
    public void create(ServletWebRequest request) throws Exception {
        //生成验证码
        T validateCode = generate(request);
        //保存验证码
        save(request, validateCode);
        //发送验证码
        send(request, validateCode);
    }

    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述): 生成验证码实现
    * @date 2019/1/25 0025 下午 4:26
    */
    private T generate(ServletWebRequest request) {
        //先转成大写
        String type = getValidateCodeType(request).toString().toLowerCase();
        //拼接实现类的简称
        String generatorName = type + IValidateCodeGenerator.class.getSimpleName();
        //根据简称查找实现类
        IValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            log.info("验证码生成器:generatorName={}不存在",generatorName);
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (T) validateCodeGenerator.generateCode(request);
    }


    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述):保存验证码（redis、session等）
    * @date 2019/1/25 0025 下午 4:26
    */
    private void save(ServletWebRequest request, T validateCode) {
        request.getRequest().getSession().setAttribute(getSessionKey(request), validateCode);
    }

    /**
    * User (作者): MRui
    * TODO (描述)：构建验证码放入session、redis等时的key
    * Data：2019-01-25 23:27
    */
    private String getSessionKey(ServletWebRequest request) {
        return Constants.SESSION_KEY_PREFIX + getValidateCodeType(request).toString().toUpperCase();
    }

    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述):发送验证码
    * @date 2019/1/25 0025 下午 4:27
    */
    protected abstract void send(ServletWebRequest request, T validateCode) throws Exception;


    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述): 获取验证码类型(sms/image)
    * @date 2019/1/25 0025 下午 4:27
    */
    private ValidateCodeEnum getValidateCodeType(ServletWebRequest request) {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeEnum.valueOf(type.toUpperCase());
    }

    /**
    * @author (作者) ma_rui
    * @Description: TODO(描述): 校验验证码
    * @date 2019/1/25 0025 下午 4:16
    */
    @SuppressWarnings("unchecked")
    @Override
    public void validate(ServletWebRequest servletWebRequest) {
        /* 获取校验类型 */
        ValidateCodeEnum processorType = getValidateCodeType(servletWebRequest);
        /* 获取sessionKey */
        String sessionKey = getSessionKey(servletWebRequest);
        /* 获取session中校验的的类型imageCode/smsCode */
        T codeInSession = (T) servletWebRequest.getRequest().getSession()
                .getAttribute(sessionKey);

        String codeInRequest;
        try {
            /* 获取验证码的值 */
            codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(),
                    processorType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(processorType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(processorType + "验证码不存在");
        }

        if (codeInSession.isPeriod()) {
            servletWebRequest.getRequest().getSession().removeAttribute(sessionKey);
            throw new ValidateCodeException(processorType + "验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(processorType + "验证码不匹配");
        }

        servletWebRequest.getRequest().getSession().removeAttribute(sessionKey);

    }
}
